<template>
  <div>
    <div class="delo">
      <div class="return">
        <span @click="returns"><i class="el-icon-back"></i>返回</span>
      </div>
      <div class="info">基本信息</div>
      <el-form :model="form" ref="form" :rules="rules" class="form" label-width="150px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="联系人姓名：" prop="cupName">
              <el-input v-model="form.cupName" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="联系电话：" prop="cupPhone">
              <el-input v-model="form.cupPhone" oninput="value=value.replace(/[^\d.]/g,'')" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="所属客户：" prop="customerByCustomId.cusName">
              <el-input v-model="form.customerByCustomId.cusName" v-on:click.native="cus=true" title="点击选择客户" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="性别：" prop="cupSex">
              <el-radio-group v-model="form.cupSex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="是否为首要联系人：" prop="delivery">
              <el-switch v-model="delivery"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="QQ：" prop="cupQq">
              <el-input v-model="form.cupQq" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="邮箱：" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" prop="cupEmail">
              <el-input v-model="form.cupEmail" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="地址：" prop="cupAddressArea">
              <v-distpicker :province="form.cupAddressProvince" @province="cupChangeProvince"
                            :city="form.cupAddressCity" @city="cupChangeCity"
                            :area="form.cupAddressArea" @area="cupChangeArea"
                            class="distpicker-address-wrapper"></v-distpicker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 40px">
          <el-col :span="10">
            <el-form-item label="备注：" prop="cupRemark">
              <el-input type="textarea" :rows="4" v-model="form.cupRemark" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="街道信息：" prop="cupXxaddress">
              <el-input v-model="form.cupXxaddress" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5" >
            <el-form-item label="职务：" prop="cupPost">
              <el-input v-model="form.cupPost" style="width: 220px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <el-button type="primary" @click="saveLinkman('form')" style="margin-left: 350px;margin-bottom: 35px">保存</el-button>
    </div>
<!--    选择客户弹框-->
    <el-dialog
      title="选择客户"
      :visible.sync="cus">
      <el-row>
        <el-col :span="4">
          <el-input
            placeholder="请输入客户名称" @change="serchCustomer" style="width: 180px;cursor: pointer;margin-left: 420px;"
            v-model="input4" clearable onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;" suffix-icon="el-icon-search" size="small">
          </el-input>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table ref="multipleTable" :data="cusTable" height="250">
            <el-table-column width="55" fixed>
              <template slot-scope="scope">
                <el-radio v-model="radio" :label="scope.row.customId" @change="getCustomerRow(scope.row)">
                  {{''}}
                </el-radio>
              </template>
            </el-table-column>

            <el-table-column fixed prop="cusName" label="客户名称" width="180">
            </el-table-column>

            <el-table-column prop="customEmpid.empName" label="负责人">
            </el-table-column>

            <el-table-column prop="typeId.typeName" label="客户类型" width="120">
            </el-table-column>

            <el-table-column prop="customTime" label="创建日期" width="180">
              <template slot-scope="scope">
                {{ scope.row.customTime | formatDate}}
              </template>
            </el-table-column>
          </el-table>
          <!--        分页-->
          <div class="page">
            <el-pagination
              :page-sizes="sizes"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalSize"
              :page-size="pageSize"
              :current-page.sync="currPage"
              @current-change="pageChange"
              @size-change="sizeChange">
            </el-pagination>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="cusOK" size="small">确 定</el-button>
        <el-button @click="cus = false" size="small">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {formatTimeToStr} from '@/assets/format'
import VDistpicker from 'v-distpicker'
export default {
  name: 'CuAddLinkman',
  components: { VDistpicker },
  data: function () {
    // 查询联系电话是否重复
    var checkedCupPhone = (rule, value, callback) => {
      if(this.updateCupPhone == value){
        // 如果修改联系人信息时没有修改联系人电话，就不做校验
        callback();
      }else{
        this.$axios.get("http://localhost:8088/vue/select-cupphone",{params:{cupPhone:value}})
          .then(v=>{
            console.log(v.data)
            if(v.data != null && v.data != ""){
              callback(new Error("联系电话重复！请重新输入"))
            }else{
              callback()
            }
          }).catch()
      }
    };
    return {
      updateCupPhone:'',//修改联系人时的联系人电话
      form: {
        cupId:'',
        cupName: '', // 联系人姓名
        cupPhone: '', // 联系电话
        cupRemark: '', // 备注
        cupSex: '男', // 男女单选框
        cupQq: '', // 微信
        customerByCustomId: {// 对应客户
          customId:'',
          cusName:'',
        },
        cupAddressProvince: '', // 地址
        cupAddressCity:'',
        cupAddressArea:'',
        cupXxaddress: '', // 详细地址
        cupEmail: '',
        cupMaster:'' //是否是首要联系人
      },
      rules:{
        cupName:[
          {required:true, message:'请输入联系人名称',trigger:'change'}
        ],
        cupPhone:[
          { required:true, message: '请输入联系电话', trigger: 'change'},
          { pattern: /^1[3456789]\d{9}$/,message: '请输入正确的联系电话', trigger:'change'},
          {validator:checkedCupPhone,trigger: 'change'}
        ],
        cupAddressArea:[
          { required:true, message: '请输入联系地址', trigger: 'change'},
        ],
        cupXxaddress:[
          {required: true, message: '请输入详细地址!', trigger: 'change' },
        ],
        'customerByCustomId.cusName':[
          { required: true, message: '请选择对应客户', trigger: 'change' }
        ],
        cupEmail:[
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,message: '请输入正确的邮箱', trigger:'change'}
        ]
      },
      delivery: false,
      cus: false,
      input4: '', // 合并客户的搜索框
      radio: 0, // 单选框下标
      customer:[], //新增时选中添加的客户对象
      multipleSelection: [],
      sizes: [10,20,30,40], // 客户页大小数组
      cusTable: [], //客户列表
      totalSize: 10, //     总条数
      currPage: 1, //     默认第一页
      pageSize: 5 //      页大小
    }
  },
  created: function () {
    if(this.$route.query.culinkman != null && this.$route.query.culinkman != ""){
      this.form=this.$route.query.culinkman
      // 方便自定义校验
      this.updateCupPhone=this.form.cupPhone
    }
    this.pageSize = this.sizes[0] // 默认第一个页大小
    this.init(this.currPage, this.pageSize) // 初始化客户
  },
  methods: {
    saveLinkman (formName) { // 保存联系人信息按钮
      this.$refs[formName].validate((valid) => {
        if (valid) {//如果通过验证
          if (this.delivery == true) {
            this.form.cupMaster = 1
          } else {
            this.form.cupMaster = 0
          }
          console.log(this.form)
          var culinkman = JSON.stringify({culinkman: this.form})
          this.$axios.post("http://localhost:8088/vue/add-linkman", this.qs.stringify({culinkman: culinkman}))
            .then(() => {
              if (this.form.cupId != null && this.form.cupId != "" && this.form.cupId != 0) {
                this.$message.success("编辑成功")
              } else {
                this.$message.success('新增成功')
              }
              this.$router.push({
                path: '/linkman'
              })
              this.clearForm()
            })
            .catch()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    cupChangeProvince(a){
      this.form.cupAddressProvince=a.value
    },
    cupChangeCity(a){
      this.form.cupAddressCity=a.value
    },
    cupChangeArea(a){
      this.form.cupAddressArea=a.value
    },
    clearForm(){
      this.form= {
        cupId:'',
        cupName: '', // 联系人姓名
        cupPhone: '', // 联系电话
        cupRemark: '', // 备注
        cupSex: '男', // 男女单选框
        cupQq: '', // 微信
        customerByCustomId: {// 对应客户
          customId:'',
          cusName:'',
        },
        cupAddressProvince: '', // 地址
          cupAddressCity:'',
          cupAddressArea:'',
          cupXxaddress: '', // 详细地址
          cupEmail: '',
          cupMaster:'' //是否是首要联系人
      },
      this.delivery= false
    },
    init (currPage, pageSize, input4) {
      this.$axios.get('http://localhost:8088/vue/have-type', {params: {page: currPage, size: pageSize, cusName: input4}})
        .then(v => {
          this.cusTable = v.data.rows
          this.totalSize = v.data.total
        })
        .catch(v => {
          alert('访问失败！' + v.data)
        })
    },
    pageChange (page) { // 客户切换页码
      this.init(page, this.pageSize, this.input4)
    },
    sizeChange (pageSize) { // 客户页大小改变
      this.init(1, pageSize, this.input4)
      this.pageSize = pageSize
    },
    serchCustomer () { // 客户模糊查询、条件查询
      this.init(1, this.pageSize, this.input4)
    },
    //单选框选中的行
    getCustomerRow(val){
      this.customer=[];//单选框每次只能选择一个，所以每次选中之前要先清空
      this.customer.push(val);
      window.console.log(this.customer[0].customId)
    },
    cusOK(){ // 确定选中客户
      if(this.customer==null || this.customer==""){
        this.$message("请选择客户")
      }else {
        this.form.customerByCustomId.cusName=this.customer[0].cusName
        this.form.customerByCustomId.customId=this.customer[0].customId
        this.cus=false
      }
    },
    returns(){
      this.$router.push({
        path:'/linkman'
      })
      this.clearForm()
    }
  },
  watch:{
    $route(){
      if(this.$route.query.culinkman != null && this.$route.query.culinkman != ""){
        if(this.$route.query.culinkman.cupMaster == 1){
          this.delivery= true
        }else{
          this.delivery= false
        }
        this.form=this.$route.query.culinkman
        // 方便自定义校验
        this.updateCupPhone=this.form.cupPhone
      }
    }
  },
  filters: {// 日期格式化
    formatDate: function (time) {
      if (time != null && time != '') {
        var date = new Date(time)
        return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }
  }
}
</script>

<style scoped>
  .return{
    border-right:1px solid #ccc;
    width:70px;
    color:#777;
    font-size: 13px;
    margin-left:10px;
    margin-top:10px;
    cursor: pointer;
  }

  a{
    text-decoration: none;
  }

  a:active{
    color: black;
  }

  .delo{
    width: 100%;
    min-height: 650px;
    border: 1px solid #D3DCE6;
    background: white;
    font-size: 14px;
  }

  .form .el-row{
    margin-left: 140px;
  }

  .info{
    font-size:14px;
    border-left: 6px solid #409eff;
    width:80px;
    height:24px;
    text-align: center;
    margin-top: 15px;
    margin-left: 30px;
  }

  .page{
    margin-top:10px;
    float: right;
    margin-right: 20px;
  }
</style>
<style>
  .distpicker-address-wrapper select {
    width: 90px;
  }
</style>
